<?php

namespace app\common\model;

use app\common\model\auth\AuthAdminModel;

class FileModel extends BaseModel
{
    protected $table = 't_file';

    //删除校验关联关系表是否存在关联数据
    protected $checkDelJoinTable = [
        't_info_article|文章' => "cover_file_id=%s"
    ];

    const TYPE_IMG = 1;
    const TYPE_FILE = 2;
    const TYPE_VIDEO = 3;
    public $type = [
        self::TYPE_IMG => '图片',
        self::TYPE_FILE => '文件',
        self::TYPE_VIDEO => '视频'
    ];

    /**
     * 删除素材
     * @param string $ids
     * @return bool
     */
    public function delFile($ids)
    {
        $errorMsg = [];
        $this->startTrans();
        try {
            $ids = explode(',', $ids);
            $data = $this->whereIn('id', $ids)->select()->column(null, 'id');
            foreach ($ids as $k => $v) {
                $num = $k + 1;
                $info = $data[$v] ?? [];
                if (!$info) {
                    $errorMsg[] = "第{$num}个素材信息不存在或已删除";
                    continue;
                }

                if ((new AuthAdminModel)->where('head_img', $info['path'])->find()) {
                    $errorMsg[] = "第{$num}个素材已被管理员头像占用，不可删除";
                    continue;
                }

                if ($this->checkDelIsExistJoinData($info['id'])) {
                    $errorMsg[] = "第{$num}个素材" . $this->getError();
                }
            }

            if (empty($errorMsg)) {
                $this->whereIn('id', array_column($data, 'id'))->delete();
            }

            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            return $this->setError($e->getMessage());
        }

        if (!empty($errorMsg)) {
            return $this->setError($errorMsg);
        }

        return true;
    }

    /**
     * 获取文件信息
     * @param int $fileId
     * @param string $field
     * @return array
     */
    public function getFileByInfo($fileId, $field = '*')
    {
        $fileInfo = $this->where('id', $fileId)->find();
        if ($fileInfo) {
            $fileInfo['size'] = get_file_size($fileInfo['size']);
            $fileInfo['url'] = get_file_url($fileInfo['path']);
        }

        return $fileInfo;
    }

    /**
     * 获取文件数据
     * @param string $fileIds
     * @return array
     */
    public function getFileByData($fileIds)
    {
        $fileData = $this->whereIn('id', explode(',', $fileIds))->select()->toArray();
        foreach ($fileData as $k => $v) {
            $fileData[$k]['size'] = get_file_size($v['size']);
            $fileData[$k]['url'] = get_file_url($v['path']);
        }

        return $fileData;
    }

}